package com.amita.ez.service.impl;


import com.amita.ez.entity.SysUser;
import com.amita.ez.service.IUserInfoService;
import com.github.benmanes.caffeine.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

@Service
public class UserInfoService implements IUserInfoService {


    @Autowired
    Cache<String, Object> caffeineCache;



    @Override
    public void put(String token, SysUser sysUser) {

        String username = sysUser.getUsername();

        List<String> keys = new ArrayList<>();
        //1. remove all others
        ConcurrentMap<String, Object> map = caffeineCache.asMap();
        for (Map.Entry<String, Object> it : map.entrySet()) {
            String key = it.getKey();
            SysUser userInfo1 = (SysUser) it.getValue();
            String username1 = userInfo1.getUsername();
            if(username.equals(username1)){
                keys.add(key);
            }
        }

        for (String key : keys) {
            map.remove(key);
        }


        //2. put new key
        caffeineCache.put(token, sysUser);

    }

    @Override
    public SysUser getByToken(String token) {

//        Object ifPresent = caffeineCache.getIfPresent(token);
        SysUser userInfo = (SysUser) caffeineCache.asMap().get(token);
        return userInfo;
    }

    @Override
    public void remove(String token) {

    }
}
